import {
  Body,
  Request,
  Query,
  Controller,
  HttpException,
  Post,
  Req,
  UseFilters,
  UseGuards,
  Header,
  Get,
} from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { AuthGuard } from '@nestjs/passport';
import { ApiBearerAuth, ApiOperation, ApiTags } from '@nestjs/swagger';
import { AuthService } from './auth.service';
import { WebLoginDto } from './dto/web.login.dto';
import { ApiConfig, MiniProgramApi, ApiConfigKit } from 'tnwx';
import { MiniLoginDto } from './dto/mini-program-login.dto';
import { defaultConfig } from '@game/config/config';
import { ApiFail } from '@common/utils';
import { AmountChangeTypeEnum } from '@common/enum/user.enum';
import { User } from '@common/database/entity/user.entity';

const envTxt = {
  WEB: '网站用户',
  WEAPP: '微信用户',
  ALIPAY: '支付宝用户',
  H5: 'WAP用户',
};

@ApiTags('MINI-登录')
@Controller()
export class AuthController {
  constructor(
    private jwtService: JwtService,
    private authServe: AuthService,
  ) {}

  @Get('getOpenId')
  @ApiOperation({ summary: '获取OpenId' })
  async getOpenIdAction(@Query() miniLoginDto: MiniLoginDto) {
    let sessionData: any = {};
    // 获取 CODE
    const code = miniLoginDto.code;
    const platform = miniLoginDto.platform;

    console.log('code', miniLoginDto);

    sessionData = await MiniProgramApi.code2Session(
      defaultConfig.weixin.appid,
      defaultConfig.weixin.secret,
      miniLoginDto.code,
    );

    console.log(sessionData);

    if (!sessionData.openid) {
      throw new ApiFail(403, '登录失败');
    }
    return sessionData;
  }

  @Post('login')
  @ApiOperation({ summary: '小程序OpenId登录' })
  @Header('x-forwarded-for', 'defineHeader')
  @Header('x-real-ip', 'defineHeader')
  async login(@Body() miniLoginDto: MiniLoginDto, @Request() req: Request) {
    let sessionData: any = {};
    sessionData.weixin_openId = miniLoginDto.openId;
    sessionData.ip = miniLoginDto.ip;
    const userInfo = miniLoginDto.userInfo;

    // console.log('user:', req.body);
    // console.log('miniLoginDto:', miniLoginDto);

    if (!sessionData.weixin_openId) {
      throw new ApiFail(403, '登录失败');
    }
    const env_type = miniLoginDto.platform || 'WEAPP';
    const ip = req.headers['x-forwarded-for'] || req.headers['x-real-ip'];
    console.log(sessionData.openId, userInfo);
    const currentTime = new Date().getTime();
    const clientIp = sessionData.ip || ip;

    // 根据openId查找用户是否已经注册
    let user:User = await this.authServe.getUser(sessionData.weixin_openId);
    console.log('user:', user);

    if (!user) {
      // 注册
     const newdata= await this.authServe.add({
        nickName: envTxt[env_type] + this.randomString(8),
        password: this.randomString(6) + '',
        registerTime: currentTime+"", //这个需要记录 统计需要
        registerIp: clientIp,
        lastLoginTime: currentTime+"",
        lastLoginIp: clientIp,
        bid:this.randomString(6) + '',
        weixin_openId: sessionData.weixin_openId,
        amount: 100, // todo: 这里是注册默认赠送积分，需要做成配置
      });
      user = await this.authServe.getUser(sessionData.weixin_openId);
      console.log('user2:', user);

      if (!user) {
        throw new ApiFail(403, '用户不存在');
      }
      // 开启免费创建 免费30天
      const isFree = await this.authServe.getSysConfig('isFree');

      const current = new Date().getTime();
      const end = current + 30 * 3600 * 24 * 1000;
      await this.authServe.addChargeRecord({
        userId: user.id,
        orderSn: this.randomString(9),
        start_time: current,
        role: isFree.is_open_charge ? 0 : -1,
        count: 1,
        changeAmount:100,
        changeType: AmountChangeTypeEnum.Gifts,
        end_time: end,
      });
    }

    sessionData.userId = user.id;
    sessionData.bId = user.bid;
    console.log('sessionData:', sessionData);

    const sessionKey = this.jwtService.sign({ ...sessionData });
    if (!sessionKey) {
      throw new ApiFail(403, '登录失败');
    }
    sessionData.avatar = user.avatar;
    sessionData.nickName = user.nickName;
    sessionData.amount = user.amount;
    delete sessionData.weixin_openId;
    const data = {
      lastLoginTime: currentTime,
      lastLoginIp: clientIp,
      weixin_openId: user.weixin_openId,
      is_new: 0,
    };
    await this.authServe.update(data);

    return {
      token: sessionKey,
      userInfo: sessionData,
      is_new: user.is_new,
    };
  }

  randomString(e) {
    e = e || 10;
    const t = '0123456789';
    const a = t.length;
    let n = '';
    for (let i = 0; i < e; i++) n += t.charAt(Math.floor(Math.random() * a));
    return n;
  }
}
